package com.knight.jdk8.stream;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

/**
 * 实现一个这样的业务：将Set集合中的每个值转换成Map的可以和值
 * {"hello","world","hello world"}
 * [{"hello":"hello"},{"world":"world"},{"hello world":"hello world"}]
 *
 * @Description:
 * @author: knight
 * @Date: 2019-05-23 21:09
 */
public class MyCollector2<T> implements Collector<T, Set<T>, Map<T, T>> {
    @Override
    public Supplier<Set<T>> supplier() {
        System.out.println("supplier invoker");
        return () -> {
            System.out.println("Perform supplier");
            return new HashSet<T>();
        };
    }

    @Override
    public BiConsumer<Set<T>, T> accumulator() {
        System.out.println("accumulator invoker");
        return (item1, item2) -> {
            System.out.println("Perform accumulator");
            item1.add(item2);
        };
    }

    @Override
    public BinaryOperator<Set<T>> combiner() {
        System.out.println("accumulator invoker");

        return (item1, item2) -> {
            System.out.println("Perform combiner");
            item1.addAll(item2);
            return item1;
        };
    }

    @Override
    public Function<Set<T>, Map<T, T>> finisher() {
        System.out.println("finisher invoker");
        return (item) -> {
            System.out.println("Perform finisher");
            Map<T, T> result = new HashMap<>(2);
            item.forEach(str -> {
                result.put(str, str);
            });
            return result;
        };
    }

    @Override
    public Set<Characteristics> characteristics() {
        System.out.println("characteristics invoker");
        return Collections.unmodifiableSet(EnumSet.of(Characteristics.UNORDERED));
    }

    public static void main(String[] args) {
        List<String> list = Arrays.asList("hello", "world", "welcome","hello");
        HashSet<String> hashSet = new HashSet<>();
        hashSet.addAll(list);
        Map<String, String> collect = hashSet.stream().collect(new MyCollector2<>());

        System.out.println(collect);
    }
}
